<template>
  <div class="w-25 mx-auto p-3">
    <h5 class="my-4 text-center">登录账户</h5>
    <validate-form ref="formRef">
      <validate-form-item label="邮箱">
        <validate-input
          type="text"
          v-model="state.email"
          :rules="rules.email"
          placeholder="请输入邮箱"
        ></validate-input>
      </validate-form-item>
      <validate-form-item label="密码">
        <validate-input
          type="password"
          v-model="state.password"
          :rules="rules.password"
          placeholder="请输入密码"
        ></validate-input>
      </validate-form-item>
      <div class="form-text mb-3">
        <a href="/register" class="">还没有账户？去注册一个新的吧！</a>
      </div>
      <template #submit>
        <div class="d-grid gap-2">
          <button class="btn btn-primary" @click.prevent="handleSubmit">
            登 录
          </button>
        </div>
      </template>
    </validate-form>
  </div>
</template>
<script lang="ts">
import { DefineComponent, defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import ValidateInput from '@/components/ValidateInput.vue'
import ValidateForm from '@/components/ValidateForm.vue'
import ValidateFormItem from '@/components/ValidateFormItem.vue'
import messageCreate from '@/components/MessageCreate'
import { IRules, IStore } from '@/types/index'
export default defineComponent({
  name: 'Login',
  components: {
    ValidateInput,
    ValidateForm,
    ValidateFormItem
  },
  setup() {
    const store = useStore<IStore>()
    const router = useRouter()
    const rules: IRules = {
      email: [
        { type: 'required', message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      password: [{ type: 'required', message: '请输入密码', trigger: 'blur' }]
    }
    const state = reactive({
      email: '',
      password: ''
    })
    const formRef = ref<null | DefineComponent>(null)
    const handleSubmit = () => {
      const valid: boolean = formRef.value?.handleSubmit()
      if (valid) {
        store
          .dispatch('loginAndGet', state)
          .then(() => {
            messageCreate(
              {
                type: 'success',
                message: '登录成功，2秒后跳转到首页'
              },
              () => {
                router.push('/')
              }
            )
          })
          .catch((e) => {
            console.log(e)
          })
      }
    }
    return {
      state,
      rules,
      formRef,
      handleSubmit
    }
  }
})
</script>
